<template>
  <el-dialog :title="title" :visible.sync="visible" @closed="closedPuls">
    <el-form ref="form" :rules="rules" :model="form">
      <el-form-item prop="name" label="角色名称" :label-width="formLabelWidth">
        <el-input v-model="form.name" autocomplete="off" />
      </el-form-item>
      <el-form-item
        prop="description"
        label="角色描述"
        :label-width="formLabelWidth"
      >
        <el-input v-model="form.description" autocomplete="off" />
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="celForm">取 消</el-button>
      <el-button type="primary" @click="submitForm">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
/* eslint-disable */
import { addRole, editRoleById } from '@/api/setting'
export default {
  name: 'SettingDialog',
  data() {
    return {
      // 表单数据
      form: {
        name: '',
        description: ''
      },
      // 宽度
      formLabelWidth: '120px',
      // 弹框
      visible: false,
      rules: {
        name: [
          { required: true, message: '角色名称不能为空', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '角色描述不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    title() {
      // return this.form.id ? '编辑角色' : '新增角色'
      if (this.form.id) {
        return '编辑角色'
      } else {
        return '新增角色'
      }
    }
  },
  methods: {
    // 点击外部清空表单
    closedPuls() {
      this.form = { name: '', description: '' }
    },
    // 取消
    celForm() {
      this.visible = false
      this.form = { name: '', description: '' }
    },
    // 提交表单
    submitForm() {
      this.$refs.form.validate(async valid => {
        if (valid) {
          // 判断走那个逻辑
          if (this.form.id) {
            //  编辑
            await editRoleById(this.form)
            this.$message.success('编辑成功')
          } else {
            // 新增
            await addRole(this.form)
            this.$message.success('新增成功')
          }
          // 关闭
          this.visible = false
          // 清空
          this.form = { name: '', description: '' }
          // 子组件操作父组件
          this.$parent.getData()
        } else {
          this.$message.error('格式有误，新增失败')
          return false
        }
      })
    }
  }
}
</script>

<style></style>
